package cn.xenosp.server.module.login.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.xenosp.server.common.Constant;
import cn.xenosp.server.common.Result;
import cn.xenosp.server.common.cache.Cache;
import cn.xenosp.server.common.sse.SseClient;
import cn.xenosp.server.common.tools.IdUtil;
import cn.xenosp.server.module.login.entity.LoginVo;
import cn.xenosp.server.module.user.entity.SysUser;
import cn.xenosp.server.module.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.server.module.login.service
 * 作者：   TongHui
 * 创建时间: 2024-12-20 15:20
 * 描述: TODO
 * 版本: 1.0
 */
@Service
public class LoginService {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    Cache redisCache;

    public Result login(LoginVo loginVo){
        SysUser user = sysUserService.getByUsername(loginVo.getUsername());
        if (ObjectUtil.isEmpty(user)){
            return Result.error("账号或密码错误","");
        }
        if (!user.getPassword().equals(SaSecureUtil.md5(loginVo.getUsername()+loginVo.getPassword()))){
            return Result.error("密码错误！","");
        }
        List<Map<String, Object>> list = sysUserService.userGetResources(user.getId());
        List<Map<String, Object>> rootMenus = new ArrayList<>();
        for (Map<String, Object> map : list) {
            if (map.get("parentId").equals("0")){
                rootMenus.add(buildMenuItem(map,list));
            }
        }
        listSort(rootMenus);
        Map<String,Object> map = new HashMap<>();
        map.put("user", user);
        map.put("remember", loginVo.isRemember());
        map.put("response", list);
        map.put("menu", rootMenus);

        StpUtil.login(user.getId(),loginVo.isRemember());
        String token = StpUtil.getTokenValue();
        redisCache.set(Constant.TOKEN+"_"+token,map,StpUtil.getTokenTimeout());
        StpUtil.getSession().set("user", user);
        return Result.OK("登录成功",map);
    }


    public Result logout(){
        String tokenValue = StpUtil.getTokenValue();
        Map<String,Object> map = (Map<String, Object>) redisCache.get(Constant.TOKEN+"_"+tokenValue);
        SysUser user = (SysUser) map.get("user");
        SseClient.close(user.getId());
        redisCache.del(Constant.TOKEN+"_"+tokenValue);
        StpUtil.logout();
        return Result.OK("","");
    }

    public void refresh(){
        String tokenValue = StpUtil.getTokenValue();
        Map<String,Object> map = (Map<String, Object>) redisCache.get(Constant.TOKEN+"_"+tokenValue);
        SysUser user = (SysUser) map.get("user");
        List<Map<String, Object>> list = sysUserService.userGetResources(user.getId());
        List<Map<String, Object>> rootMenus = new ArrayList<>();
        for (Map<String, Object> meanMap : list) {
            if (meanMap.get("parentId").equals("0")){
                rootMenus.add(buildMenuItem(meanMap,list));
            }
        }
        listSort(rootMenus);
        map.put("response", list);
        map.put("menu", rootMenus);

        redisCache.set(Constant.TOKEN+"_"+tokenValue,map,StpUtil.getTokenTimeout());
    }

    public String getImgId(){
        return IdUtil.getId();
    }
    private Map<String, Object> buildMenuItem(Map<String, Object> menu, List<Map<String, Object>> menuList) {
        Map<String, Object> item = new HashMap<>();
        item.put("title", menu.get("name"));
        item.put("icon", menu.get("icon"));
        item.put("menuId", menu.get("menuId"));
        item.put("parentId", menu.get("parentId"));
        item.put("url", menu.get("component"));
        item.put("visible", menu.get("visible"));
        item.put("type", menu.get("type"));
        item.put("sort", menu.get("sort"));
        item.put("permission", menu.get("permission"));
        List<Map<String, Object>> subMenus = new ArrayList<>();
        for (Map<String, Object> subMenu : menuList) {
            if (subMenu.get("type").equals("3")){
                continue;
            }
            if (subMenu.get("parentId").equals(menu.get("menuId"))) {
                subMenus.add(buildMenuItem(subMenu, menuList));
            }
        }
        listSort(subMenus);
        item.put("list", subMenus);
        return item;
    }

    private void listSort(List<Map<String, Object>> list){
        // 使用 Collections.sort() 结合 Comparator 来定义排序规则
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                // 从 Map 中获取 "sort" 字段的值
                Integer sort1 = Integer.valueOf(o1.get("sort").toString());
                Integer sort2 = Integer.valueOf(o2.get("sort").toString());
                // 若存在 null 值，将其视为最小值处理
                if (sort1 == null && sort2 == null) {
                    return 0;
                }
                if (sort1 == null) {
                    return -1;
                }
                if (sort2 == null) {
                    return 1;
                }
                // 比较两个 "sort" 字段的值
                return sort1.compareTo(sort2);
            }
        });
    }
}
